/*
 * Created by Jaren at 2022/2/21 20:45
 */
import 'dart:typed_data';

import 'package:inmotion_protocol/util/byte_util.dart';

class StorageInfo {

    static const int minLength = 6;

    static const int capacity2Bytes = 0;
    static const int capacity4Bytes = 1;
    static const int capacity8Bytes = 2;

    int diskIndex = 0;
    int capacityLength = 0;
    int capacity = 0;
    int remain = 0;

    int bytesLength() {
        return 1 + 1 + capacityBytesLength(capacityLength) * 2;
    }

    static int capacityBytesLength(int capacityLength) {
        switch (capacityLength) {
            case capacity2Bytes:
                return 2;
            case capacity4Bytes:
                return 4;
            case capacity8Bytes:
                return 8;
            default:
                return 2;
        }
    }


    @override
    String toString() {
        return 'StorageInfo{diskIndex: $diskIndex, capacityLength: $capacityLength, capacity: $capacity, remain: $remain}';
    }

    static StorageInfo fromBytes(Uint8ClampedList bytes, [ int offset = 0]) {
        StorageInfo storageInfo = StorageInfo();
        if (bytes.isEmpty || bytes.length < offset + minLength) {
            return storageInfo;
        }
        storageInfo.diskIndex = bytes[offset];
        offset++;
        storageInfo.capacityLength = bytes[offset];
        offset++;
        int capacityBytesLength = StorageInfo.capacityBytesLength(storageInfo.capacityLength);
        storageInfo.capacity = ByteUtil.bytes2UIntLe(bytes, offset, capacityBytesLength);
        offset += capacityBytesLength;
        storageInfo.remain = ByteUtil.bytes2UIntLe(bytes, offset, capacityBytesLength);
        return storageInfo;
    }
}